import { Component, OnDestroy, OnInit } from '@angular/core';
import { Subject } from 'rxjs';
import { map, takeUntil } from 'rxjs/operators';
import { ActivatedRoute } from '@angular/router';
import { RecordVal, User } from '@services/data-types/member.type';
import { SheetService } from '@services/sheet.service';
import { MemberService, RecordType } from '@services/member.service';
import { BatchActionsService } from '@store/batch-actions.service';
import { Song } from '@services/data-types/common.type';
import { SongService } from '@services/song.service';
import { NzMessageService } from 'ng-zorro-antd';
import { select, Store } from '@ngrx/store';
import { getCurrentSong, getPlayer } from '@store/selectors/player.selector';
import { findIndex } from '@utils/array';
import { AppStoreModule } from '@store/index';


@Component({
  selector: 'app-record-detail',
  templateUrl: './record-detail.component.html',
  styleUrls: ['./record-detail.component.less']
})
export class RecordDetailComponent implements OnInit, OnDestroy {
  user: User;
  userRecords: RecordVal[];
  currentIndex = -1;
  recordType = RecordType.weekData;
  private currentSong: Song;
  private destroy$ = new Subject<void>();
  constructor(
    private route: ActivatedRoute,
    private store$: Store<AppStoreModule>,
    private songServe: SongService,
    private sheetService: SheetService,
    private memberService: MemberService,
    private nzMessageServe: NzMessageService,
    private batchActionsService: BatchActionsService
  ) {
    this.route.data.pipe(map(res => res.record)).subscribe(([userInfo, userRecords]) => {
      this.user = userInfo;
      this.userRecords = userRecords;
    });
  }

  ngOnInit() {
    this.listenCurrentSong();
  }
  onChangeType(type: number) {
    if (this.recordType !== type) {
      this.recordType = type;
      this.memberService.getUserRecord(this.user.profile.userId.toString(), type).subscribe(records => {
        this.userRecords = records;
      });
    }
  }
  onAddSong([song, isPlay]) {
    if (!this.currentSong || song.id !== this.currentSong.id) {
      this.songServe.getSongList(song).subscribe(list => {
        // 如果当前歌曲没有url，就不再执行insertSong这个Action
        if (list.length) {
          this.batchActionsService.insertSong(list[0], isPlay);
        } else {
          this.nzMessageServe.create('warning', '无url');
        }
      });
    }
  }
  private listenCurrentSong() {
    this.store$.pipe(select(getPlayer), select(getCurrentSong), takeUntil(this.destroy$))
    .subscribe(song => {
      this.currentSong = song;
      if (song) {
        const songs = this.userRecords.map(item => item.song);
        this.currentIndex = findIndex(songs, song);
      } else {
        this.currentIndex = -1;
      }
    });
  }
  ngOnDestroy(): void {
    this.destroy$.next();
    this.destroy$.complete();
  }
}
